﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Forms;

namespace Shop
{
    public partial class Form1 : Form
    {
        Shop shop;
        List<Calc> calc;
        public Form1()
        {
            InitializeComponent();
            shop = new Shop("My Whim");
            calc = new List<Calc>();
            Loads();
            ShowDataTovar();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = shop.name;
        }

        private void addBTN_Click(object sender, EventArgs e)
        {
            addBTN.Text = "Add";
            panel.Enabled = true; ;
            if ((nameOfProduct.Text != "") && (cost.Text != "") && (placeOfCreation.Text != "") && (description.Text != "")
                && (valueOfMeasure.Text != "") && (dateOfCreation.Value < DateTime.Now) && (period.Value > DateTime.Now))
            {
                switch (measure.Text)
                {
                    case "kg":
                        shop.AddTovar(Convert.ToDouble(valueOfMeasure.Text),
                            nameOfProduct.Text, Convert.ToDouble(cost.Text), dateOfCreation.Value,
                            period.Value, placeOfCreation.Text, description.Text, Convert.ToInt16(procent.Text));
                        break;
                    case "count":
                        shop.AddTovar(Convert.ToInt16(valueOfMeasure.Text),
                            nameOfProduct.Text, Convert.ToDouble(cost.Text), dateOfCreation.Value,
                            period.Value, placeOfCreation.Text, description.Text, Convert.ToInt16(procent.Text));
                        break;
                }
                ClearDataProducts();
                ShowDataTovar();
                Save();
            }
        }

        private void clearBTN_Click(object sender, EventArgs e)
        {
            ClearDataProducts();
        }

        private void ClearDataProducts()
        {
            nameOfProduct.Clear();
            cost.Clear();
            placeOfCreation.Clear();
            description.Clear();
            valueOfMeasure.Clear();
            procent.Clear();
        } // очистка полей ввода
        void ShowDataTovar()
        {
            List<String> temp = new List<string>(); // список товаров 
            List<int> NumberTovars = new List<int>(); // список ID товаров

            NumberTovars = shop.NumberTovar();

            NumberSelect.Items.Clear();
            temp = shop.ListOfTovar();
            ListProd.Items.Clear();
            if (temp.Count > 0)
            {
                for (int i = 0; i < temp.Count; i++)
                {
                    ListProd.Items.Add(temp[i]);
                    NumberSelect.Items.Add(NumberTovars[i]);
                }
            }


        } // отображение данных
        void Save()
        {
            FileStream fs = new FileStream("shop.save", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            BinaryFormatter bf = new BinaryFormatter();

            //сериализация
            bf.Serialize(fs, shop);
            fs.Close();
            fs = new FileStream("calc.save", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
            bf = new BinaryFormatter();

            //сериализация
            bf.Serialize(fs, calc);
            fs.Close();
        } // Сохранение данных 
        void Loads()// загрузка данных
        {
            try
            {
                FileStream fs = new FileStream("shop.save", FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryFormatter bf = new BinaryFormatter();
                shop = (Shop)bf.Deserialize(fs);
                fs.Close();

                fs = new FileStream("calc.save", FileMode.Open, FileAccess.Read, FileShare.Read);
                bf = new BinaryFormatter();
                calc = (List<Calc>)bf.Deserialize(fs);
                fs.Close();
            }
            catch (Exception e)
            {
                Save();
            }
        }
        private void tabPage1_Enter(object sender, EventArgs e) // событие, когда таб становится активным
        {
            ShowDataTovar();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e) // сохранение при закрытии формы
        {
            Save();
        }

        private void updateBTN_Click_1(object sender, EventArgs e)
        {
            if (NumberSelect.Text == "")
                return;
            Tovar temp = shop.getTovar(Convert.ToInt16(NumberSelect.Text));
            if (temp.name == null)
                return;
            panel.Enabled = false;
            addBTN.Text = "Save";


            nameOfProduct.Text = temp.name;
            cost.Text = temp.cost.ToString();
            description.Text = temp.descrioption;
            period.Value = temp.period;
            dateOfCreation.Value = temp.dateOfCreate;
            placeOfCreation.Text = temp.placeOfCreate;
            procent.Text = temp.procent.ToString();
            if (temp is TovarOfCount)
            {
                measure.Text = "count";
                TovarOfCount temps = (TovarOfCount)temp;
                valueOfMeasure.Text = temps.count.ToString();
            }
            else
            {
                measure.Text = "kg";
                TovarOfWeight temps = (TovarOfWeight)temp;
                valueOfMeasure.Text = temps.weight.ToString();
            }

            shop.DeleteTovar(Convert.ToInt16(NumberSelect.Text));
            NumberSelect.Text = "";
        }

        private void deleteBTN_Click_1(object sender, EventArgs e)
        {
            shop.DeleteTovar(Convert.ToInt16(NumberSelect.Text));
            ShowDataTovar();
            Save();
            NumberSelect.Text = "";
        }

        private void StartSellBTN_Click(object sender, EventArgs e)
        {


            if (!SellPanel.Enabled)
            {
                StartSellBTN.Text = "End Sell";
                SellPanel.Enabled = true;
                Calc tempCalc = new Calc();
                tempCalc.id_calc = calc.Count;
                tempCalc.date_calc = DateTime.Now;
                calc.Add(tempCalc);
            }
            else
            {
                StartSellBTN.Text = "Start Sell";
                SellPanel.Enabled = false;
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            String tempCount="0";
            TovarList.Items.Clear();
            if (codeTovar.Text.Trim() == "")
            {
                return;
            }
            Tovar temp = shop.getTovar(Int16.Parse(codeTovar.Text));
            if (temp.name == null)
            {
                CountPanel.Enabled = false;
                return;
            }
           
            CountPanel.Enabled = true;
            if (temp is TovarOfCount)
            {
                measureSell.Text = "count";
                TovarOfCount temps = (TovarOfCount)temp;
                if (temps.count <= 0)
                {
                    tempCount = temps.count.ToString();
                    TovarList.Items.Add("Tovar was Sold");
                    CountPanel.Enabled = true;
                }
            }
            else
            {
                measureSell.Text = "kg";
                TovarOfWeight temps = (TovarOfWeight)temp;
                if (temps.weight <= 0)
                {
                    TovarList.Items.Add("Tovar was Sold");
                    CountPanel.Enabled = true;
                    tempCount = temps.weight.ToString();
                }
            }
            TovarList.Items.Add(temp.name + " " + temp.costOfRealization + " " + temp.period + " \n "+ tempCount +" "  + temp.descrioption);
        }

        private void SellBTN_Click(object sender, EventArgs e)
        {
            CountPanel.Enabled = false;
            TovarList.Items.Clear();
            shop.decCount(Int32.Parse(codeTovar.Text), Int16.Parse(countValue.Text));
            calc[calc.Count - 1].id_tovar.Add(Int32.Parse(codeTovar.Text));
            calc[calc.Count - 1].cost += Int16.Parse(countValue.Text)*(shop.getTovar(Int32.Parse(codeTovar.Text))).costOfRealization;
        }

        private void countValue_TextChanged(object sender, EventArgs e)
        {
            if (countValue.Text.Trim() != "")
            {
                Tovar temp = shop.getTovar(Int16.Parse(codeTovar.Text));
            if (temp is TovarOfCount)
            {
                if (Int16.Parse(countValue.Text) > ((TovarOfCount)temp).count)
                    SellBTN.Enabled = false;
                else
                    SellBTN.Enabled = true;
            }
            else
            {
                if (Int16.Parse(countValue.Text) > ((TovarOfWeight)temp).weight)
                    SellBTN.Enabled = false;
                else
                    SellBTN.Enabled = true;
            }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (calc.Count > 0)
            {
                SellsList.Items.Clear();
                for (int i = 0; i < calc.Count; i++)
                {
                    SellsList.Items.Add(calc[i].id_calc + " Cost: "+calc[i].cost+" Date: "+calc[i].date_calc);
                    for (int j = 0; j < calc[i].id_tovar.Count; j++)
                    {
                        try
                        {
                            Tovar temp = shop.getTovar(calc[i].id_tovar[i]);
                            SellsList.Items.Add(" - - - - " + temp.name + " Cost: " + temp.costOfRealization);
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
        }

    }
}
